#include <stdio.h>
#include <linux/unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <pthread.h>
#include "test_barrier_header.h"


void *thread_function( void *ptr );

int main(int argc, char *argv[])
{
	
	int j;
	int id =(int)barriercreate(2);
	if(id < 0)
	{
		perror("barriercreate: ");
		printf("Barrier Create error \n");
		return -1;
	}
	printf("Barrier Created\n");
	
	pthread_t threads[10];
	printf("pthread declared\n");

	for(j=0;j<3;j++)
	{
		pthread_create( &threads[j], NULL, thread_function, (void*) &id);
		printf("pthread %d created\n", j);
	}
	
	pthread_join( threads[0], NULL);
	pthread_join( threads[1], NULL);
	pthread_join( threads[2], NULL);

	printf("joined pthreads\n");
	
	printf("Destroying barrier\n");
	barrierdestroy(id);
	printf("DESTROYED\n");
	return 0;
}


void *thread_function( void* ptr )
{
  printf("in thread_function\n");
         int* idptr = (int *) ptr;
	 printf("%d\n",*idptr);
	 //int id=(int)ptr;
	 printf("Thread number %ld\n", pthread_self());
	 printf("Before Wait\n");
	 if(barrierwait(*idptr) != 0)
	   printf("error in barrier wait!!!!\n");
	 printf("Wait Over- Now Returning to main %ld\n", pthread_self());
	 
     
}

